//
//  KaiYaoViewController.m
//  EcmDoctor
//
//  Created by Mac on 16/3/2.
//  Copyright © 2016年 张进. All rights reserved.
//

#import "KaiYaoViewController.h"
#import "MedicineOneTableViewCell.h"
#import "AppUtils.h"
#import "UIImageView+AFNetworking.h"
#import "MedicineListViewController.h"
#import "MedicineListm.h"
#import "Presibmedicinem.h"
#import "SVProgressHUD.h"
@interface KaiYaoViewController ()<UITableViewDataSource,UITableViewDelegate,myProtocol2,myProtocol3,UITextFieldDelegate,UIAlertViewDelegate>
{
    __weak IBOutlet UIScrollView *_myScv;
    __weak IBOutlet UIView *_myView;
    
    __weak IBOutlet NSLayoutConstraint *myTvHeight;
    __weak IBOutlet NSLayoutConstraint *myViewHeight;
    __weak IBOutlet UITextView *_zdTextView;
    __weak IBOutlet UIView *_zdView;
    __weak IBOutlet UITextView *_bzTextView;
    __weak IBOutlet UIView *_bzView;
    __weak IBOutlet UITableView *_myTv;
    __weak IBOutlet UILabel *_customerAge;
    __weak IBOutlet UILabel *_customerSex;
    __weak IBOutlet UILabel *_customerName;
    __weak IBOutlet UIImageView *_customericon;
    __weak IBOutlet UIView *_iconView;
    UITextField *_numtextField;
}
@end

@implementation KaiYaoViewController

- (void)viewDidLoad {
    [super viewDidLoad];
   
    _myTv.separatorStyle=UITableViewCellSeparatorStyleNone;
    
    _zdView.layer.borderColor=[UIColor colorWithRed:153/255.0 green:144/255.0 blue:134/255.0 alpha:1].CGColor;
    _bzView.layer.borderColor=[UIColor colorWithRed:153/255.0 green:144/255.0 blue:134/255.0 alpha:1].CGColor;
    _bzTextView.text=@"请输入备注";
    [self setheight];
    self.automaticallyAdjustsScrollViewInsets = NO;
     //self.view.backgroundColor = [AppUtils getBackground];
    self.navigationItem.titleView=[AppUtils generateNavigationItemTitleViewWithTitle:@"推荐治疗方案"];
      self.navigationItem.rightBarButtonItem = [AppUtils generateNavigationBarButtonWithTitle:@"完成" withTarget:self action:@selector(done)];
    UIImage *tableIcon = [UIImage imageNamed:@"btn_back"];
    self.navigationItem.leftBarButtonItem =[[UIBarButtonItem alloc] initWithImage:tableIcon style:UIBarButtonItemStylePlain target:self action:@selector(changeToNavRootController)];
    self.navigationItem.leftBarButtonItem.tintColor = [UIColor colorWithPatternImage:tableIcon];
    _iconView.layer.borderColor=[UIColor lightGrayColor].CGColor;
    _customerAge.text=self.user_age;
    _customerName.text=self.user_name;
    _customerSex.text=self.user_sex;
    NSLog(@"--------------%@",self.user_icon);
    [_customericon   setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://ecm-user.oss-cn-beijing.aliyuncs.com/image/%@",self.user_icon]] placeholderImage:[UIImage imageNamed:@"icon"]];

    
    // Do any additional setup after loading the view.
}
-(void)done
{
    Presibmedicinem *presibmedicinem=[[Presibmedicinem alloc]init];
    NSMutableArray *drugAry=[NSMutableArray array];
    NSMutableArray *bzAry=[NSMutableArray array];
    NSString *numStr=[self createUUID];
    for(int i=0;i<_dataAry.count;i++)
    {  MedicineListm *medicineListm=_dataAry[i];
        //NSDictionary *dic=[NSDictionary dictionaryWithObjectsAndKeys:<#(nonnull id), ...#>, nil]
        CureSchemeChildInfom * childDrug=[[CureSchemeChildInfom alloc]init];
        NSIndexPath *indexPath=[NSIndexPath indexPathForRow:1 inSection:0];
        MedicineOneTableViewCell  *medicinecell =[_myTv cellForRowAtIndexPath:indexPath];

        childDrug.child_info_id=numStr;
        childDrug.drug_id=medicineListm.drug_sid;
        childDrug.drug_name=medicineListm.goods_name;
        childDrug.drug_money=@"";
        childDrug.drug_type=@"1";
        childDrug.payType=@"1";
        childDrug.durg_ishealthc=@"1";
        childDrug.all_num=_numtextField.text;
        
        childDrug.drug_num=medicinecell.medicineNuml.text;
        if(medicinecell.medicineNuml.text.intValue>=1)
            [bzAry addObject:@"1"];
        childDrug.drug_unit=medicineListm.product_unit;
        [drugAry addObject:childDrug];
        
    }
    if(_numtextField.text.intValue>=1)
    {
         [bzAry addObject:@"1"];
        
    }
     NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
     formatter.dateFormat = @"yyyy-MM-dd HH:mm";
    NSDate *date=[NSDate date];
     NSString * _strData = [formatter stringFromDate:date];
   NSString *docId= [SSKeychain passwordForService:APP_SERVICE_NAME account:APP_DOCTORINFOID_KEY];
    presibmedicinem.childInfos=[NSMutableArray arrayWithArray:drugAry];
    presibmedicinem.curescheme_info_id=@"";
    presibmedicinem.user_info_id=self.user_info_id;
    NSLog(@"===========%@",self.user_info_id);
    presibmedicinem.doctor_info_id=docId;
    presibmedicinem.user_relation_id=@"";
    presibmedicinem.info_date=_strData;
    presibmedicinem.all_money=@"";
    presibmedicinem.ask_info_id=self.askId;
    presibmedicinem.ask_remark=_bzTextView.text;
    presibmedicinem.ask_diagnose=_zdTextView.text;
    presibmedicinem.cure_type=@"1";
    if(bzAry.count==_dataAry.count+1)
   [Presibmedicinem insertCureSchemeInfowithclientDrugInfo:presibmedicinem success:^(NSNumber *num) {
       if(num.intValue==1)
       {
           [SVProgressHUD showImage:nil status:@"已开药"];
           [self changeToNavRootController];
       }
   } failure:^(NSError *error) {
       NSLog(@"%@",error.localizedDescription);
   }];
    else
    {
        [SVProgressHUD showImage:nil status:@"所需药品数量未填写完整"];
    }
}
- (NSString *)createUUID
{
    CFUUIDRef uuidObject = CFUUIDCreate(kCFAllocatorDefault);
    CFStringRef uuidStrRef = CFUUIDCreateString(kCFAllocatorDefault, uuidObject);
    NSString *uustStr = [NSString stringWithFormat:@"%@",uuidStrRef];
    NSString *UUID= [uustStr stringByReplacingOccurrencesOfString:@"-" withString:@""];
    CFRelease(uuidObject);
    
    return UUID;
}
-(void)setheight
{
    if(_dataAry.count)
   {
       myTvHeight.constant=(_dataAry.count+1)*60+60;
       _myTv.rowHeight=60;
       myViewHeight.constant=100+130*2+41*3+10+(_dataAry.count+1)*60+60;
       _myScv.contentSize=CGSizeMake(kScreenWidth, 100+130*2+41*3+10+(_dataAry.count+1)*60+60);
   }
    else
    {
    myTvHeight.constant=130;
    _myTv.rowHeight=130;
    myViewHeight.constant=100+130*3+41*3+10;
    _myScv.contentSize=CGSizeMake(kScreenWidth, 100+130*3+41*3+10);
    }
}
-(void)textFieldDidBeginEditing:(UITextField *)textField
{
    CGFloat x=_myScv.frame.origin.x;
    CGFloat Y=_myScv.frame.origin.y;
    CGFloat W=_myScv.frame.size.width;
    CGFloat H=_myScv.frame.size.height;
    [UIView animateWithDuration:0.3 animations:^{
        _myScv.frame=CGRectMake(x, Y-200, W, H);
    }];
   
}
-(void)textFieldDidEndEditing:(UITextField *)textField
{
    CGFloat x=_myScv.frame.origin.x;
    CGFloat Y=_myScv.frame.origin.y;
    CGFloat W=_myScv.frame.size.width;
    CGFloat H=_myScv.frame.size.height;
    [UIView animateWithDuration:0.3 animations:^{
        _myScv.frame=CGRectMake(x, Y+200, W, H);
    }];
    

}
-(void)changeToNavRootController{
    [self.navigationController popViewControllerAnimated:YES];
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{   if(_dataAry.count)
    return _dataAry.count+1;
    else
    return 1;
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if(_dataAry.count)
    { return 60;
    }
    else
        return 0;
}

-(UIView*)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    if(_dataAry.count)
{
    
    UIView *headerView1=[[UIView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth-30, 60)];
    headerView1.backgroundColor=[UIColor clearColor];
    UIView *headerView=[[UIView alloc]initWithFrame:CGRectMake(0, 5, kScreenWidth-30, 50)];
    headerView.backgroundColor=[UIColor colorWithRed:255/255.0 green:248/255.0 blue:239/255.0 alpha:1];
    UILabel *label=[[UILabel alloc]initWithFrame:CGRectMake(0, 20, 100, 20)];
    label.text=@"中药饮片";
    label.backgroundColor=[UIColor clearColor];
    label.textColor=[UIColor blackColor];
    [headerView addSubview:label];
    if(_numtextField==nil)
    {
    _numtextField=[[UITextField alloc]initWithFrame:CGRectMake(kScreenWidth-30-80, 23, 70, 20)];
    _numtextField.tag=909;
    _numtextField.text=@"1";
    _numtextField.delegate=self;
    _numtextField.keyboardType = UIKeyboardTypeNumberPad;
    _numtextField.backgroundColor=[UIColor whiteColor];
    _numtextField.returnKeyType=UIReturnKeyDone;
    }
    [headerView addSubview:_numtextField];
    UILabel *label1=[[UILabel alloc]initWithFrame:CGRectMake(kScreenWidth-30-70-60, 20, 60, 20)];
    label1.text=@"数量：";
    label1.textAlignment=NSTextAlignmentRight;
    label1.backgroundColor=[UIColor clearColor];
    label1.textColor=[UIColor blackColor];
    [headerView addSubview:label1];
    [headerView1 addSubview:headerView];
    return headerView1;
}
    else
        return nil;
}

-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell;
    MedicineOneTableViewCell *mediconecell;
    if(_dataAry.count)
    {
       
        if(indexPath.row==_dataAry.count)
        {
            static NSString *iden = @"iden";
            UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:iden];
            if (cell == nil) {
                cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:iden];
            }

            UIButton *but=[UIButton buttonWithType:UIButtonTypeCustom];
            but.frame=CGRectMake(0, 0, kScreenWidth-30, 60);
            [but setImage:[UIImage imageNamed:@"addpic2"] forState:UIControlStateNormal];
            but.backgroundColor=[UIColor colorWithRed:255/255.0 green:248/255.0 blue:239/255.0 alpha:1];
            [but addTarget:self action:@selector(medicineList) forControlEvents:UIControlEventTouchUpInside];
            [cell addSubview:but];
            return cell;
        }
       else
       {
        mediconecell=[tableView dequeueReusableCellWithIdentifier:@"medicinetwo" forIndexPath:indexPath];
        MedicineListm *medicinelist=_dataAry[indexPath.row];
        mediconecell.medicineNamel.text=medicinelist.goods_name;
           mediconecell.medicineNuml.text=@"1";
       }
        
    }
    else
    {
    mediconecell=[tableView dequeueReusableCellWithIdentifier:@"medicineone" forIndexPath:indexPath];
       
    mediconecell.layer.borderColor=[UIColor colorWithRed:153/255.0 green:144/255.0 blue:134/255.0 alpha:1].CGColor;

    
    }
    mediconecell.delegate=self;
    mediconecell.selectionStyle=UITableViewCellSelectionStyleNone;
    cell=mediconecell;
    return cell;
}

-(void)deledateMedicineWith:(NSInteger)row
{
    
    [_dataAry removeObjectAtIndex:row];
    
    if(!_dataAry.count)
    {
        [self setheight];
        [_myTv reloadData];
       
    }
    else
    {
    NSIndexPath*indexp=[NSIndexPath indexPathForRow:row inSection:0];
     NSArray *selectIndexPaths = [NSArray arrayWithObject:indexp];
    [_myTv beginUpdates];
    [_myTv deleteRowsAtIndexPaths:selectIndexPaths withRowAnimation:UITableViewRowAnimationTop];
    [self setheight];
    [_myTv endUpdates];
    }
    
}
-(void)refresh
{
    [self setheight];
    [_myTv reloadData];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
-(void)medicineList
{
    UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"请选择药品种类" message:@"" delegate:self cancelButtonTitle:@"中药饮片" otherButtonTitles: nil];
    [alert show];
    
   
}
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
     [self performSegueWithIdentifier:@"medicineList" sender:nil];
}
-(void)refreshMedicineListWith:(NSArray *)dataAry
{   [_dataAry removeAllObjects];
    _dataAry=[NSMutableArray arrayWithArray:dataAry];
    [self refresh];
}
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
    if ([segue.identifier isEqualToString:@"medicineList"]) {
        MedicineListViewController *mlv;
        mlv= segue.destinationViewController;
        if(_dataAry)
            mlv.selectdAry=[NSMutableArray arrayWithArray:_dataAry];
        
        mlv.delegate=self;
    }

    
}


@end
